<template>
  <div class="select-table relative flex flex-1 flex-col overflow-hidden" v-bind="$attrs">
    <!-- <padding-container class="flex-1 overflow-hidden !pb-[0px] !pt-[5px]"> </padding-container> -->
    <!-- border: true, -->
    <!-- height="100%" -->
    <div class="flex-1 overflow-hidden px-[16px]">
      <el-table
        ref="table"
        :key="refreshKey"
        class="overflow-x-auto"
        height="100%"
        :row-key="rowKey"
        default-expand-all
        :data="list"
        v-bind="{ ...$attrs }"
        :default-sort="{ prop: 'storder', order: 'ascending' }"
        v-on="$listeners"
        @selection-change="handleSelectionChange"
        @select="handleSelect"
        @select-all="handleSelectAll"
      >
        <el-table-column v-if="showIndex" type="index" label="序号" fixed="left" width="60" :index="handleIndex" />
        <el-table-column v-if="showSelection" type="selection" width="50" align="center" reserve-selection />
        <el-table-column
          v-for="item in cols"
          :key="item.prop"
          :align="item.align || 'center'"
          v-bind="item.props"
          show-overflow-tooltip
          v-on="item.listeners"
        >
          <template v-if="item.slotHeader" slot="header">
            <slot :name="item.headername"> </slot>
          </template>
          <template slot-scope="scope">
            <slot v-if="item.slotName" :name="item.prop" v-bind="scope"> </slot>
            <span v-else-if="item.KV_MAP">{{ $store.state.data.KV_MAP[item.KV_MAP][scope.row[item.prop]] }}</span>
            <template v-else>
              {{
                (scope.row[item.prop] === 0 || scope.row[item.prop] === "0"
                  ? 0
                  : scope.row[item.prop] || item.nullString || "") +
                (item.unit ? (scope.row[item.unit] ? `（${scope.row[item.unit]}）` : "" || "") : "")
              }}
            </template>
          </template>
        </el-table-column>
        <slot name="otherSlot" />
        <template slot="empty">
          <t-empty-data />
        </template>
      </el-table>
    </div>
    <div v-if="page" class="h-[68px]"></div>

    <div class="s-t-b absolute bottom-0 right-0 mt-[1px] flex h-[64px] w-full items-center justify-end">
      <el-pagination
        v-if="page"
        ref="pagination"
        class="mr-[16px] flex-1 text-right"
        background
        :total="total === -1 ? allData?.length : total"
        :page-sizes="pageSizes"
        :layout="layout"
        :page-size="pageSize"
        :current-page="pageNumber"
        @size-change="handleSizeChange"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>

<script>
// import utils from "@/utils/utils";
export default {
  name: "SelectTable",
  props: {
    //列
    cols: {
      type: Array,
      default: () => {
        return [];
      },
    },
    //使用分页
    page: {
      type: Boolean,
      default: true,
    },
    // pageSize: {
    //   type: Number,
    //   default: 20,
    // },
    //表格数据
    tableData: {
      type: Array,
      default: () => {
        return null;
      },
    },
    //表格查询参数
    tableParams: {
      type: Object,
      default: null,
    },
    //获取表格高度方法
    getTableHeight: {
      type: Function,
      default: () => {
        return 800;
      },
    },
    //获取表格数据方法
    getTableData: {
      type: Function,
      default: null,
    },

    pageNumberString: {
      type: String,
      default: () => "pageIndex",
    },
    pageSizeString: {
      type: String,
      default: () => "length",
    },
    showIndex: {
      type: Boolean,
      default: false,
    },
    showSelection: {
      type: Boolean,
      default: false,
    },
    rowKey: {
      type: String,
      default: "id",
    },
    refreshKey: {
      type: Boolean,
      default: false,
    },
    atuoQuery: {
      type: Boolean,
      default: false,
    },

    // 组件布局
    layout: {
      type: String,
      default: "total, sizes, prev, pager, next, jumper",
    },
  },

  data() {
    return {
      height: 0, //表格高度
      pageNumber: 1, //当前页
      pageSizes: [10, 20, 30, 40, 50], //每页条数
      pageSize: 10, //每页条数
      list: [], //
      total: -1, //总条数
      // refreshKey: false,
      multipleSelection: [],
      selectionData: {},
    };
  },

  computed: {
    allData() {
      return this.tableData || [];
    },
  },

  watch: {
    getTableData: {
      immediate: false,
      handler(newValue) {
        if (newValue) {
          //分页
          if (this.page) {
            this.pageChange();
          } else {
            //
          }
        }
      },
    },
    tableData: {
      // immediate: true,
      handler(newValue) {
        if (newValue) {
          //分页
          if (this.page) {
            this.pageChange();
          } else {
            this.list = newValue;
          }
        }
      },
    },
  },
  mounted() {
    if (this.atuoQuery) {
      this.pageChange();
    }
    // this.updateTableHeight();
    // window.onresize = () => {
    //   return (() => {
    //     this.updateTableHeight();
    //   })();
    // };
  },
  updated() {
    this.$nextTick(() => {
      this.$refs["table"].doLayout();
    });
  },
  destroyed() {
    window.onresize = null;
  },
  methods: {
    updateTableHeight() {
      this.$nextTick(() => {
        this.height = this.getTableHeight() - (this.page ? this.$refs.pagination.$el.offsetHeight : 0);
      });
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize || this.pageSize;
      this.pageChange();
    },
    pageChange(pageNumber) {
      this.pageNumber = pageNumber || this.pageNumber;
      if (this.getTableData) {
        this.getTableData({
          ...{
            [this.pageNumberString]: this.pageNumber,
            [this.pageSizeString]: this.pageSize,
          },
          ...this.tableParams,
        }).then((res) => {
          const { content: list = [], totalElements: total = 0 } = res;
          this.list = list;
          this.total = total;
        });
      } else {
        const start = (this.pageNumber - 1) * this.pageSize;
        this.list = [];
        for (let index = start; index < start + this.pageSize; index++) {
          this.allData[index] && this.list.push(this.allData[index]);
        }
      }
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
      // selection.forEach(s => {
      //   let l = this.list.find(f => f[this.rowKey] == s);
      //   if (l) {
      //     this.selectionData[s] = l;
      //   }
      // });
      // this.$emit("SelectionChange", utils.clone(this.multipleSelection));
    },
    handleSelect(selection, row) {
      // let { multipleSelection, rowKey } = this;
      // //删除
      // if (!selection.some(s => s[rowKey] == row[rowKey])) {
      //   const index = multipleSelection.findIndex(
      //     f => f[rowKey] == row[rowKey],
      //   );
      //   if (index > -1) {
      //     multipleSelection.splice(index, 1);
      //     //('current-select', multipleSelection);
      //   }
      // }
    },

    handleSelectAll(selection) {
      // let { multipleSelection, rowKey, list } = this;
      // if (selection.length == 0) {
      //   for (let index = 0; index < list.length; index++) {
      //     const select = list[index];
      //     const i = multipleSelection.findIndex(
      //       f => f[rowKey] == select[rowKey],
      //     );
      //     if (i > -1) {
      //       multipleSelection.splice(i, 1);
      //     }
      //   }
      //   //('current-select', multipleSelection);
      // }
    },

    handleIndex(index) {
      if (this.page) {
        return (this.pageNumber - 1) * this.pageSize + (index + 1);
      } else {
        return index + 1;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-table--border::after,
.el-table--group::after,
.el-table::before,
::v-deep .el-table__fixed::before,
::v-deep .el-table__fixed-right::before {
  background-color: transparent;
}

::v-deep span.el-pagination__total {
  height: 32px;
  line-height: 32px;
}
</style>
